'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Loader2 } from 'lucide-react';
import { SpecialtyTableData } from '@/lib/types';

export default function EquipmentTablePage() {
  const [specialtyData, setSpecialtyData] = useState<SpecialtyTableData[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchEquipmentData = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/equipment-table');
        if (!response.ok) {
          throw new Error('获取设备数据失败');
        }
        const data = await response.json();
        setSpecialtyData(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : '发生了未知错误');
      } finally {
        setLoading(false);
      }
    };

    fetchEquipmentData();
  }, []);

  return (
    <div className="p-4 space-y-4">
      <Card>
        <CardHeader>
          <CardTitle>设备总表</CardTitle>
        </CardHeader>
        <CardContent>
          {loading && (
            <div className="flex justify-center items-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
              <p className="ml-2">正在加载数据...</p>
            </div>
          )}
          {error && <p className="text-red-500">{error}</p>}
          {!loading && !error && (!specialtyData || specialtyData.length === 0) && (
            <p>未找到可显示的数据。</p>
          )}
        </CardContent>
      </Card>
      
      {!loading && !error && specialtyData && specialtyData.map((data, index) => (
        <Card key={index}>
          <CardHeader>
            <CardTitle>{data.specialty}</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  {data.headers.map((header, index) => (
                    <TableHead key={index}>{header}</TableHead>
                  ))}
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.rows.map((row, rowIndex) => (
                  <TableRow key={rowIndex}>
                    {row.map((cell: any, cellIndex: number) => (
                      <TableCell key={cellIndex}>{cell}</TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ))}
    </div>
  );
} 